<?php

/**
 * @author Grover Campos
 * @version 1.0
 * @created 03-ago-2009 06:43:08 p.m.
 */
class Gtux_Model_Gateway_Variable extends Gtux_Model_Gateway_Abstract 
{
  /**
   * Devuelve la tabla
   *
   * @return Gtux_Model_Table_Variable
   */
	public function getDbTable()
	{
    if (null == $this->_dbTable) 
    {
      $this->setDbTable('Gtux_Model_Table_Variable');
    }
    return $this->_dbTable;
	}

	/**
	 * Elimina una variable
	 * 
	 * @param Gtux_Model_Variable $variable
	 * @param int
	 */
	public function delete(Gtux_Model_Abstract $variable)
	{
    $where = $this->getDbTable()
                  ->getAdapter()
                  ->quoteInto('id_variable = ?', $variable->getIdVariable());
    return $this->getDbTable()->delete($where);
	}

	public function fetchAll()
	{
    $rs      = $this->getDbTable()->fetchAll();
    $entries = array();
    foreach ($rs as $row) 
    {
      $entries[$row->id_variable] = new Gtux_Model_Variable(null, $row);
    }
    return $entries;
	}

	/**
	 * 
	 * @param Gtux_Model_Variable $variable
	 * @return int
	 */
	public function insert(Gtux_Model_Abstract $variable)
	{
	  $data = array(
	   'nombre' => $variable->getNombre(),
	   'valor'  => $variable->getValor()
	  );
	  $id = $variable->getIdVariable();
	  if (NULL == $id) 
	  {
	  	return $this->getDbTable()->insert($data);
	  }
	  return false;
	}

	public function update(Gtux_Model_Abstract $variable)
	{
	  $data = array();
	  if (strlen($variable->getNombre())>0) 
	  {
	  	$data['nombre'] = $variable->getNombre();
	  }
	  if (strlen($variable->getValor())>0) 
	  {
	  	$data['valor'] = $variable->getValor();
	  }
	  $id = $variable->getIdVariable();
	  if (NULL !== $id && sizeof($data)>0) 
	  {
	  	$where = $this->getDbTable()
	  	              ->getAdapter()
	  	              ->quoteInto('id_variable = ?', $variable->getIdVariable());
      return $this->getDbTable()->update($data, $where);	  	              
	  }
	  return false;
	}

  /**
   * @see Gtux_Model_Gateway_Abstract::save()
   *
   * @param Gtux_Model_Abstract $model
   */
  public function save(Gtux_Model_Abstract $variable)
  {
    $id = $variable->getIdVariable();
    if (NULL == $id) 
    {
      return $this->insert($variable);
    }
    else 
    {
      return $this->update($variable);
    }    
  }

}
?>